package net.pimpas.web.jsf.page.controller;

import java.io.Serializable;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

public final class PageControllerPhaseListener implements Serializable, PhaseListener {

	private static final long serialVersionUID = 2911708946083783060L;
	
	private void publishPageController( FacesContext context ) {
		
		HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
		String viewId = context.getViewRoot().getViewId().replace(".jsp", "");
		
		if(PageControllerVisitor.pages.containsKey(viewId))
			try {
				PageControl control = PageControllerVisitor.pages.get(viewId).getAnnotation(PageControl.class);
				
				if(request.getAttribute(control.name()) != null) {
					// its equal?!
					PageController pg = (PageController) request.getAttribute(control.name());
					PageControl control2 = pg.getClass().getAnnotation(PageControl.class);
					if(control.pageName().equals(control2.pageName())) return;
				}
				
				PageController controller = PageControllerVisitor.pages.get(viewId).newInstance();
				request.setAttribute(control.name(), controller);
			} catch(Exception e) {
				throw new RuntimeException(e);
			}
	}

	public void afterPhase(PhaseEvent event) {this.publishPageController(event.getFacesContext());}


	public void beforePhase(PhaseEvent event) {}

	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}
}